package com.demo.io.tool;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class MarkdownTool {
    public static String parseMarkdown(String filename) throws IOException {
        //
        File f = new File(filename);
        if(!f.exists() || !f.canRead()){
            throw new IOException("markdown 文件不存在或不可读");
        }
        FileInputStream fis = new FileInputStream(f);
        byte[] bytes = new byte[fis.available()]; // 读取内容字节数组
        fis.read(bytes);
        fis.close();
        // 将字节数组转成字符串
        String markdownText =new String(bytes);
        StringBuffer sb = new StringBuffer();
        String[] lines=  markdownText.split("\n");
        for (String line : lines) {
            if(line.startsWith("######")){
                sb.append("<h6>").append(line.substring(6)).append("</h6>");
            }else if(line.startsWith("#####")){
                sb.append("<h5>").append(line.substring(5)).append("</h5>");
            }else if(line.startsWith("####")){
                sb.append("<h4>").append(line.substring(4)).append("</h4>");
            }else if(line.startsWith("###")){
                sb.append("<h3>").append(line.substring(3)).append("</h3>");
            }else if(line.startsWith("##")){
                sb.append("<h2>").append(line.substring(2)).append("</h2>");
            }else if(line.startsWith("#")){
                sb.append("<h1>").append(line.substring(1)).append("</h1>");
            }else sb.append(line + "\n");
        }
        System.out.println(sb);
        return sb.toString();
    }

    public static void main(String[] args) throws IOException {
        parseMarkdown("test.md");
    }
}
